package com.hschinese.pronunciation.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.bean.PlayAssetData;
import com.hschinese.pronunciation.bean.UserInfo;
import com.hschinese.pronunciation.db.DBHelper;
import com.hschinese.pronunciation.interfaces.PlayCompleteListener;
import com.hschinese.pronunciation.interfaces.VolumeListener;
import com.hschinese.pronunciation.model.UserInfoModel;
import com.hschinese.pronunciation.utils.Constant;
import com.hschinese.pronunciation.utils.HsSoundUtil;
import com.hschinese.pronunciation.utils.Logger;
import com.hschinese.pronunciation.utils.MD5Utils;
import com.hschinese.pronunciation.utils.SharedPreferenceUtils;
import com.hschinese.pronunciation.utils.SimpleRecordUtil;
import com.hschinese.pronunciation.utils.ThreadPoolUtil;
import com.hschinese.pronunciation.utils.UIUtils;
import com.hschinese.pronunciation.utils.UrlUtil;
import com.hschinese.pronunciation.utils.Utils;
import com.hschinese.pronunciation.utils.WebRequestUtil;
import com.hschinese.pronunciation.widget.HsDialog;
import com.hschinese.pronunciation.widget.MyPopupWindow;
import com.hschinese.pronunciation.widget.RoundProgressBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;

import studychinese.utils.ToastUtils;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    private ImageView mPlayOrgImageView;
    private ImageView mRecordImageView;
    private ImageView mPlayRecorderImageView;
    private ImageView mTitleImageView;

    private TextView mStartView;
    private TextView mLoginOrRegView;

    private SharedPreferenceUtils mSharedPrefUtil;
    private boolean wantExit = false;
    private boolean isLogined = false;
    private RoundProgressBar mPlayOrgBar = null;
    private RoundProgressBar mPlayStandardBar = null;

    private boolean hasRecorded = false;
    private HsDialog mDialog = null;
    private MyPopupWindow mPopupWindow;
    private View baseView = null;
    private VolumeListener mVolumeListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        mPopupWindow = new MyPopupWindow(MainActivity.this);
        if (!Utils.isNetworkValid(MainActivity.this)) {
            UIUtils.showToast(MainActivity.this, getResources().getString(R.string.network_unavalible), Toast.LENGTH_SHORT);
        }
        initVolumeListener();
        play();
    }

    private void initialData() {
        mSharedPrefUtil = SharedPreferenceUtils.getInstance(MainActivity.this);
        isLogined = mSharedPrefUtil.getIsLogined();
        File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/msc/ise.wav");
        if (f.exists()) {
            f.delete();
        }
        hasRecorded = false;
    }

    private void initViews() {
        baseView = findViewById(R.id.main_base_line);
        mPlayOrgImageView = (ImageView)findViewById(R.id.play_org);
        mRecordImageView = (ImageView)findViewById(R.id.record_voice);
        mPlayRecorderImageView = (ImageView)findViewById(R.id.play_record);
        mTitleImageView = (ImageView)findViewById(R.id.title_img);
        mStartView = (TextView) findViewById(R.id.start_use);
        mLoginOrRegView = (TextView) findViewById(R.id.login_or_register);
        mPlayOrgBar = (RoundProgressBar)findViewById(R.id.main_play_org_bar);
        mPlayStandardBar = (RoundProgressBar)findViewById(R.id.main_play_record_bar);

        mPlayOrgImageView.setOnClickListener(this);
        mPlayRecorderImageView.setOnClickListener(this);
        mStartView.setOnClickListener(this);
        mLoginOrRegView.setOnClickListener(this);
        mPlayRecorderImageView.setVisibility(View.INVISIBLE);
        mPlayStandardBar.setVisibility(View.INVISIBLE);

        setTitleImage();
        initTouchListener();
    }

    private void setTitleImage() {
        String la = Utils.getLanguage(MainActivity.this);
        if (Constant.LANGUAGE_JAPANESE.equals(la)) {
            mTitleImageView.setImageResource(R.drawable.ic_title_ja);
        } else if (Constant.LANGUAGE_CHINESE.equals(la)) {
            mTitleImageView.setImageResource(R.drawable.ic_title);
        } else if (Constant.LANGUAGE_KOREAN.equals(la)) {
            mTitleImageView.setImageResource(R.drawable.ic_title_ko);
        } else if (Constant.LANGUAGE_ENGLISH.equals(la)) {
            mTitleImageView.setImageResource(R.drawable.ic_title_en);
        }
    }

    private void initTouchListener() {
        mRecordImageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mRecordImageView.setImageResource(R.drawable.ic_speaker_focus);
                        // 开始录制
                        mPopupWindow.showPopupWindow(baseView);
                        startRecord();
                        break;
                    case MotionEvent.ACTION_UP:
                        // 结束录制
                        mRecordImageView.setImageResource(R.drawable.ic_speaker_unfocus);
                        stopRecord();
                        mPopupWindow.dimissPopupWindow();
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
    }

    private void initVolumeListener() {
        mVolumeListener = new VolumeListener() {
            @Override
            public void updateVolume(float volume) {
                if (mPopupWindow != null) {
                    mPopupWindow.setVolumeText(volume);
                }
            }
        };
    }

    private long startRecordTime = 0L;
    private void startRecord() {
        startRecordTime = System.currentTimeMillis();
        SimpleRecordUtil.getInstance(MainActivity.this).setVolumeListener(mVolumeListener);
        boolean b = SimpleRecordUtil.getInstance(MainActivity.this).startRecorder();
        if (!b) { // TODO 消掉PopupWindow
            mPopupWindow.dimissPopupWindow();
        }
    }

    private void stopRecord() {
        SimpleRecordUtil.getInstance(MainActivity.this).stopRecorder();
        long time = System.currentTimeMillis() - startRecordTime;
        if (time < 500) return;
        File f = new File(SimpleRecordUtil.recPath);
        if (f.exists()) {
            mPlayRecorderImageView.setVisibility(View.VISIBLE);
            mPlayStandardBar.setVisibility(View.VISIBLE);
            hasRecorded = true;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initialData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDialog != null) {
            mDialog.dismiss();
            mDialog = null;
        }
    }

    private void play() {
        mPlayOrgImageView.setImageResource(R.drawable.voice_animator);
        AnimationDrawable draw = (AnimationDrawable) mPlayOrgImageView.getDrawable();
        draw.setOneShot(true);
        draw.start();
        startTask(1.5f, draw);
        PlayAssetData data = HsSoundUtil.playAssetNew(MainActivity.this, "hello.mp3");
        updateProgress(1200);
        Logger.e("xionghy - duration: " + data.getDuration());
    }

    private int standardProgress = 0;
    private void playStandardProgress(final int duration) {
        mPlayStandardBar.setMax(duration);
        mPlayStandardBar.setProgress(standardProgress);
        new Thread(new Runnable() {
            @Override
            public void run() {
                int progressSteps = duration / 100;
                while(standardProgress <= duration){
                    standardProgress += progressSteps;
                    System.out.println(standardProgress);
                    mPlayStandardBar.setProgress(standardProgress);
                    try {
                        Thread.sleep(progressSteps);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                standardProgress = 0;
                mPlayStandardBar.setProgress(standardProgress);
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.play_org) {
            play();
        } else if (id == R.id.play_record) {
            if (hasRecorded) {
                mPlayRecorderImageView.setImageResource(R.drawable.ic_playing);
                File f = new File(SimpleRecordUtil.recPath);
                int duration = SimpleRecordUtil.getInstance(MainActivity.this).playMicFile(f);
                playStandardProgress(duration);
                SimpleRecordUtil.getInstance(MainActivity.this).setPlayCompleteListener(new PlayCompleteListener() {
                    @Override
                    public void playComplete() {
                        mPlayRecorderImageView.setImageResource(R.drawable.ic_playing);
                        mPlayRecorderImageView.setImageResource(R.drawable.ic_play);
                    }
                });
            }
        } else if (id == R.id.start_use) {
            // TODO 检查网络
            if (!Utils.isNetworkValid(MainActivity.this)) {
                UIUtils.showToast(MainActivity.this, getResources().getString(R.string.network_unavalible), Toast.LENGTH_SHORT);
                return;
            }
            // TODO 未登录的话将是游客登录
            if (!mSharedPrefUtil.getIsLogined() || mSharedPrefUtil.getuserInfo().getAnonymity()) { // 未登录或者是游客登录
                createGuestAccount();
                showWaitDialog();
            } else { // 已经登录
                startStudyEntryActivity();
            }
        } else if (id == R.id.login_or_register) {
            Logger.e("xionghy - click login btn...");
            Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
            loginIntent.putExtra("start_activity", 1);
            startActivity(loginIntent);
        }
    }

    // TOURIST_LOGIN
    // apkey language comfrom  mckey
    private void createGuestAccount() {
        HashMap<String, String> params = new HashMap<String, String>();
        String apkey =  null;
        try {
            // productID+UDID+hansheng 的MD5值大写
            apkey = MD5Utils.getMD5(Constant.PRODUCT_ID + Utils.getUniqueCode(MainActivity.this) + "hansheng");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if (apkey == null) {
            UIUtils.showToast(MainActivity.this, "生成apkey失败。", Toast.LENGTH_SHORT);
            return;
        }
        params.put("apkey", apkey.toUpperCase());
        params.put("language", Utils.getLanguage(MainActivity.this));
        params.put("productID", Constant.PRODUCT_ID);
        params.put("mckey", Utils.getUniqueCode(MainActivity.this));
        WebRequestUtil.getInstance(MainActivity.this).postRequestString(UrlUtil.TOURIST_LOGIN, params, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject json = new JSONObject(s);
                    boolean b = json.getBoolean("Success");
                    Logger.e("xionghy -- login TOURIST_LOGIN: " + json.toString());
                    if (b) {
                        JSONObject js = json.getJSONObject("User");
                        createAnonymitySuccess(js);
                        finish();
                    } else {
                        UIUtils.showToast(MainActivity.this, json.getString("Message"), Toast.LENGTH_SHORT);
                        Logger.e("xionghy -- login response: " + json.getString("Message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    if (mDialog != null) {
                        mDialog.dismiss();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Logger.e("xionghy -- login response: " + volleyError.getMessage());
                // 匿名登录失败
//                UIUtils.showToast(MainActivity.this, getResources().getString(R.string.anonymity_login_failed), Toast.LENGTH_SHORT);
                mDialog.dismiss();
            }
        });
    }

    private void createAnonymitySuccess(JSONObject json){
        try {
            UserInfo info = UserInfoModel.getInstance().getUserInfoObj(json);
            Logger.e("xionghy - create AnonymitySuccess - nEmail: " + info.getNemail());
            info.setAnonymity(true);
            // TODO save data to shared preference.
            mSharedPrefUtil.setIsLogined(true);
            mSharedPrefUtil.setUserInfo(info);
            mSharedPrefUtil.setIsLogined(true);
            startStudyEntryActivity();
        } catch (JSONException e) {
            Logger.e("xionghy - Login failed. User Data Translate Failed.");
            e.printStackTrace();
        }
    }

    private void startStudyEntryActivity() {
        Intent it = new Intent(MainActivity.this, EntryActivity.class);
        it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(it);
    }

    private void showWaitDialog() {
        mDialog = new HsDialog(MainActivity.this, R.style.pop_dialog, getResources().getString(R.string.login_dlg_msg), true, false);
        mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                WebRequestUtil.getInstance(MainActivity.this).cancelByTag(UrlUtil.LOGIN);
            }
        });
        mDialog.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if(!wantExit){
                wantExit = true;
                UIUtils.showToast(getApplicationContext(), getString(R.string.press_again_to_exit), Toast.LENGTH_SHORT);
                new Handler().postDelayed(new Runnable(){
                    public void run(){
                        wantExit = false;
                    }
                }, Constant.PERIOD_DOUBLE_CLICK_BACK);
                return false;
            }else{
                ThreadPoolUtil.getInstance().shutdownNow();
                LinkedList<Activity> allAtys = MyApplication.getInstance().getAllAtys();
                for (Activity activity : allAtys) {
                    DBHelper.getInstance(getApplicationContext()).destroy();
                    activity.finish();
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    int progress = 0;
    private void updateProgress(int time) {
        progress = 0;
        mPlayOrgBar.setProgress(progress);
        new Thread(new Runnable() {

            @Override
            public void run() {
                while(progress <= 100){
                    progress += 5;
                    mPlayOrgBar.setProgress(progress);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                progress = 0;
                mPlayOrgBar.setProgress(progress);
            }
        }).start();
    }

    private void startTask(float t, final AnimationDrawable draw) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (draw.isRunning())
                    draw.stop();
            }
        }, (int) (t * 1000));
    }
}
